import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/profile/security/password_setting/password_setting_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class PasswordSettingPage extends StatefulWidget {
  const PasswordSettingPage({super.key});

  @override
  State<PasswordSettingPage> createState() => _PasswordSettingPageState();
}

class _PasswordSettingPageState extends State<PasswordSettingPage> {
  @override
  void initState() {
    super.initState();
    context.read<PasswordSettingPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(title: const Text(AppStrings.resetPassword));
  }

  Widget _buildMainBody(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          children: [
            const SizedBox(height: 20),
            _buildOldPasswordInput(context),
            const SizedBox(height: 60),
            _buildNewPasswordInput(context),
            const SizedBox(height: 40),
            _buildMainButtonRow(context),
          ],
        ),
      ),
    );
  }

  // 提交按钮
  Widget _buildMainButtonRow(BuildContext context) {
    return SizedBox(
      height: 44,
      width: double.infinity,
      child: Selector<PasswordSettingPageLogic, bool>(
        selector: (context, logic) => logic.canSubmit,
        builder: (context, v, child) {
          return ElevatedButton(
            onPressed: v ? _mainButtonPressed : null,
            style: ButtonStyle(
              shape: WidgetStateProperty.all<RoundedRectangleBorder>(
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
              ),
            ),
            child: Text(
              AppStrings.submit,
              style: Theme.of(context).textTheme.titleMedium,
            ),
          );
        },
      ),
    );
  }

  // 提交按钮点击事件
  void _mainButtonPressed() {
    final logic = context.read<PasswordSettingPageLogic>();
    logic.submit().then((value) {
      if (value) {
        context.pop();
      }
    });
  }

  // 旧密码输入框
  Widget _buildOldPasswordInput(BuildContext context) {
    final logic = context.read<PasswordSettingPageLogic>();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          AppStrings.oldPassword,
          style: Theme.of(
            context,
          ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
        ),
        Selector<PasswordSettingPageLogic, bool?>(
          selector: (context, logic) => logic.password0Ready,
          builder: (context, ready, child) {
            final primaryColor = Theme.of(context).colorScheme.primary;
            final Widget? suffixIcon;
            if (ready != null) {
              suffixIcon = Icon(
                ready ? Icons.check : Icons.error,
                color: ready ? primaryColor : Colors.red,
              );
            } else {
              suffixIcon = null;
            }
            return TextField(
              obscureText: true,
              autofocus: true,
              controller: logic.passwordController0,
              focusNode: logic.focusNode0,
              maxLength: 20,
              buildCounter:
                  (
                    context, {
                    required currentLength,
                    required isFocused,
                    required maxLength,
                  }) {
                    return null;
                  },
              decoration: InputDecoration(
                hintText: AppStrings.passwordHintText,
                suffixIcon: suffixIcon,
              ),
            );
          },
        ),
        const SizedBox(height: 10),
        Row(
          children: [
            const Spacer(),
            GestureDetector(
              onTap: () {
                context.pushNamed(
                  AppRouter.kForgotPasswordSetting,
                  queryParameters: {'prev_route': AppRouter.kSecuritySetting},
                );
              },
              child: Text(
                AppStrings.forgotPassword,
                style: Theme.of(
                  context,
                ).textTheme.titleSmall?.copyWith(color: Colors.grey),
              ),
            ),
          ],
        ),
      ],
    );
  }

  // 新密码输入框
  Widget _buildNewPasswordInput(BuildContext context) {
    final logic = context.read<PasswordSettingPageLogic>();
    return Column(
      children: [
        _buildInputNewPassword(context, logic),
        const SizedBox(height: 20),
        _buildInputConfirmPassword(context, logic),
      ],
    );
  }

  // 新密码
  Widget _buildInputNewPassword(
    BuildContext context,
    PasswordSettingPageLogic logic,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          AppStrings.newPassword,
          style: Theme.of(
            context,
          ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
        ),
        Selector<PasswordSettingPageLogic, bool?>(
          selector: (context, logic) => logic.password1Ready,
          builder: (context, ready, child) {
            final primaryColor = Theme.of(context).colorScheme.primary;
            final Widget? suffixIcon;
            if (ready != null) {
              suffixIcon = Icon(
                ready ? Icons.check : Icons.error,
                color: ready ? primaryColor : Colors.red,
              );
            } else {
              suffixIcon = null;
            }
            return TextField(
              obscureText: true,
              controller: logic.passwordController1,
              focusNode: logic.focusNode1,
              maxLength: 20,
              buildCounter:
                  (
                    context, {
                    required currentLength,
                    required isFocused,
                    maxLength,
                  }) {
                    return null;
                  },
              decoration: InputDecoration(
                hintText: AppStrings.inputNewPassword,
                suffixIcon: suffixIcon,
              ),
            );
          },
        ),
      ],
    );
  }

  // 确认密码
  Widget _buildInputConfirmPassword(
    BuildContext context,
    PasswordSettingPageLogic logic,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          AppStrings.confirmPassword,
          style: Theme.of(
            context,
          ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
        ),
        Selector<PasswordSettingPageLogic, bool?>(
          selector: (context, logic) => logic.password2Ready,
          builder: (context, v, child) {
            final primaryColor = Theme.of(context).colorScheme.primary;
            final Widget? suffixIcon;
            if (v != null) {
              suffixIcon = Icon(
                v ? Icons.check : Icons.error,
                color: v ? primaryColor : Colors.red,
              );
            } else {
              suffixIcon = null;
            }
            return TextField(
              obscureText: true,
              controller: logic.passwordController2,
              focusNode: logic.focusNode2,
              maxLength: 20,
              buildCounter:
                  (
                    context, {
                    required currentLength,
                    required isFocused,
                    maxLength,
                  }) {
                    return null;
                  },
              // 确认密码, 输入框中的提示文案
              decoration: InputDecoration(
                hintText: AppStrings.inputConfirmPassword,
                suffixIcon: suffixIcon,
              ),
            );
          },
        ),
      ],
    );
  }
}
